package ztree;

import java.util.List;
import java.util.Map;

import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollectionUtil;

public class BuildZTree{
	 
    /**
	 *  构建单位分类树
	 */
//    public static List<TreeNode> buildDept(List<DeptDO> nodes){ 
//    	if (nodes == null){ return null; } 
//        List<TreeNode> trees = Lists.newArrayList();
//        nodes.stream().forEach(node -> trees.add(TreeNode.builder().pId(node.getParentId()).name(node.getName()).id(node.getId()).isParent(node.getHasChild() == null ? true : node.getHasChild() == 1).build()));
//        return parseTree(trees);
//    }
    
    public static List<TreeNode> parseTree(List<TreeNode> list){
    	
    	List<TreeNode> resultTree = Lists.newArrayList();
    	Map<String,TreeNode> tmpMap = Maps.newHashMap();
    	list.stream().forEach(listTmp -> tmpMap.put(listTmp.getId(), listTmp));
 
		for (int i = 0, l = list.size(); i < l; i++){
			TreeNode map = list.get(i);
			if (tmpMap.get(map.getPId()) != null && map.getId() != map.getPId()) {
				if (tmpMap.get(map.getPId()) != null && CollectionUtil.isEmpty(tmpMap.get(map.getPId()).getChildren())) {
					 tmpMap.get(map.getPId()).setChildren(Lists.newArrayList()); 
				} 
				tmpMap.get(map.getPId()).getChildren().add(list.get(i));
			} else {
				resultTree.add(list.get(i));
			}
		}
		return resultTree;
	}
    
}